package com.example.system.information.mq;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellSignalStrengthWcdma;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.example.system.information.bean.DeviceInfoRecord;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import android.telephony.CellInfo;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.SignalStrength;

import androidx.core.content.ContextCompat;


public class SystemInfoUtils {
    private static final String TAG = "SystemInfoUtils";

    /**
     * 获取系统信息
     *
     * @param context 上下文对象
     * @return 包含系统信息的DeviceInfoRecord对象
     */
    public static DeviceInfoRecord getSystemInfo(Context context) {
        DeviceInfoRecord record = new DeviceInfoRecord();
        // 获取网络类型
        record.setNetworkType(getNetworkType(context));
        // 获取网络信号强度
        record.setNetworkSignal(getNetworkSignalStrength(context));
        // 获取上行下行带宽
        record.setUpFlowPer(new BigDecimal(getCurrentUploadBandwidth()));
        record.setDownFlowPer(new BigDecimal(getCurrentDownloadBandwidth()));
        // 获取充电状态
        record.setChargeStatus(getChargeStatus(context));
        // 获取电池电量
        record.setBatteryLevel(getBatteryLevel(context));
        // 获取电池温度
        record.setBatteryTemp(new BigDecimal(getBatteryTemperature(context)));
        // 获取磁盘剩余空间
        record.setDiskUsed(getDiskUsedSpace());
        record.setDiskTotal(getDiskTotalSpace());
        // 获取内存占用和总量
        ActivityManager.MemoryInfo memoryInfo = getMemoryInfo(context);
        record.setMemUsed(memoryInfo.totalMem - memoryInfo.availMem);
        record.setMemTotal(memoryInfo.totalMem);
        // 获取CPU温度
        float cpuTemperature = getCpuTemperature();
        if (!Float.isNaN(cpuTemperature)) {
            BigDecimal bigDecimal = new BigDecimal(cpuTemperature);
            record.setCpuTemp(bigDecimal);
        } else {
            record.setCpuTemp(new BigDecimal(0));
        }
        //获取CPU占用
        record.setCpuUsed(getCpuUsage());
        //获取CPU总量
        record.setCpuTotal(getTotalCpuFrequency());
        // 获取定位状态  0L定位服务正常 1L定位服务禁用
        boolean locationServiceEnabled = isLocationServiceEnabled(context);
        if (locationServiceEnabled) {
            record.setPositionStatus(0L);
        } else {
            record.setPositionStatus(1L);
        }
        // 获取蓝牙状态
        record.setBluetoothStatus(getStatusMessage(getBluetoothStatus(context)));
        // 获取WIFI状态
        record.setWifiStatus(getWifiStatus(context));
        // 获取是否静音
        record.setMuteStatus(getMuteStatusMessage(getSoundStatus(context)));
        // 获取本次开机以来的上下行总使用流量
        record.setUpFlowTotal(getTotalTxBytes());
        record.setDownFlowTotal(getTotalRxBytes());

        return record;
    }

    /**
     * 获取网络类型
     *
     * @param context 上下文对象
     * @return 网络类型字符串
     */
    private static String getNetworkType(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) {
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                    return "WIFI";
                } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    switch (activeNetwork.getSubtype()) {
                        case TelephonyManager.NETWORK_TYPE_GPRS:
                        case TelephonyManager.NETWORK_TYPE_EDGE:
                        case TelephonyManager.NETWORK_TYPE_CDMA:
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                            return "2G";
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                            return "3G";
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            return "4G";
                        case TelephonyManager.NETWORK_TYPE_NR:
                            return "5G";
                    }
                }
            }
        }
        return "未知";
    }

    /**
     * 获取网络信号强度
     *
     * @param context 上下文对象
     * @return 网络信号强度（WiFi：0-100；移动网络：0-5；其他：-1）
     */
    public static long getNetworkSignalStrength(Context context) {
        // 获取连接管理器
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        if (networkInfo == null || !networkInfo.isConnected()) {
            return -1; // 无网络连接
        }

        // 根据网络类型获取信号强度
        switch (networkInfo.getType()) {
            case ConnectivityManager.TYPE_WIFI:
                return getWifiSignalStrength(context);
            case ConnectivityManager.TYPE_MOBILE:
                return getMobileSignalStrength(context);
            default:
                return -1; // 不支持的网络类型
        }
    }

    /**
     * 获取WiFi信号强度
     *
     * @param context 上下文对象
     * @return WiFi信号强度（0-100）
     */
    private static int getWifiSignalStrength(Context context) {
        try {
            // 获取WiFi管理器
            android.net.wifi.WifiManager wifiManager = (android.net.wifi.WifiManager)
                    context.getSystemService(Context.WIFI_SERVICE);
            android.net.wifi.ScanResult scanResult = getStrongestWifiScanResult(wifiManager);

            if (scanResult != null) {
                // 将RSSI转换为0-100的强度值
                return android.net.wifi.WifiManager.calculateSignalLevel(
                        scanResult.level, 100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取最强的WiFi信号
     *
     * @param wifiManager WiFi管理器
     * @return 最强的WiFi扫描结果
     */
    private static android.net.wifi.ScanResult getStrongestWifiScanResult(
            android.net.wifi.WifiManager wifiManager) {
        java.util.List<android.net.wifi.ScanResult> scanResults = wifiManager.getScanResults();
        if (scanResults != null && !scanResults.isEmpty()) {
            android.net.wifi.ScanResult strongestResult = scanResults.get(0);
            for (android.net.wifi.ScanResult result : scanResults) {
                if (result.level > strongestResult.level) {
                    strongestResult = result;
                }
            }
            return strongestResult;
        }
        return null;
    }

    /**
     * 获取移动网络信号强度
     *
     * @param context 上下文对象
     * @return 移动网络信号强度（0-5）
     */
    private static int getMobileSignalStrength(Context context) {
        // 检查是否有获取移动网络信号的权限
        if (!hasMobileNetworkPermission(context)) {
            Log.w("NetworkUtils", "缺少获取移动网络信号的权限");
            return -1; // 返回-1表示缺少权限
        }

        try {
            // 获取电话管理器
            TelephonyManager telephonyManager = (TelephonyManager)
                    context.getSystemService(Context.TELEPHONY_SERVICE);

            // 获取所有小区信息
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                List<CellInfo> cellInfoList = telephonyManager.getAllCellInfo();
                if (cellInfoList != null) {
                    for (CellInfo cellInfo : cellInfoList) {
                        if (cellInfo.isRegistered()) {
                            if (cellInfo instanceof CellInfoGsm) {
                                CellSignalStrengthGsm strength = ((CellInfoGsm) cellInfo).getCellSignalStrength();
                                return strength.getLevel(); // 使用getLevel()方法获取通用信号强度等级
                            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 &&
                                    cellInfo instanceof CellInfoWcdma) {
                                CellSignalStrengthWcdma strength = ((CellInfoWcdma) cellInfo).getCellSignalStrength();
                                return strength.getLevel(); // 使用getLevel()方法获取通用信号强度等级
                            } else if (cellInfo instanceof CellInfoLte) {
                                CellSignalStrengthLte strength = ((CellInfoLte) cellInfo).getCellSignalStrength();
                                return strength.getLevel(); // 使用getLevel()方法获取通用信号强度等级
                            }
                        }
                    }
                }
            }
        } catch (SecurityException e) {
            Log.e("NetworkUtils", "安全异常: " + e.getMessage());
            return -1; // 返回-1表示安全异常
        } catch (Exception e) {
            Log.e("NetworkUtils", "获取移动信号强度时出错: " + e.getMessage());
        }
        return 0; // 默认返回0表示无法获取信号强度
    }

    // 检查是否有获取移动网络信号的权限
    private static boolean hasMobileNetworkPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10及以上需要精确位置权限
            return ContextCompat.checkSelfPermission(context,
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        } else {
            // Android 9及以下需要粗略位置权限
            return ContextCompat.checkSelfPermission(context,
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        }
    }

    /**
     * 获取充电状态
     *
     * @param context 上下文对象
     * @return 充电状态（0:否 1:是）
     */
    private static int getChargeStatus(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);
        if (batteryStatus != null) {
            int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            return (status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL) ? 1 : 0;
        }
        return 0;
    }

    /**
     * 获取电池电量
     *
     * @param context 上下文对象
     * @return 电池电量百分比
     */
    private static long getBatteryLevel(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);
        if (batteryStatus != null) {
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            return (long) (level * 100 / (float) scale);
        }
        return 0;
    }

    /**
     * 获取电池温度
     *
     * @param context 上下文对象
     * @return 电池温度
     */
    private static float getBatteryTemperature(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);
        if (batteryStatus != null) {
            return batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10f;
        }
        return 0;
    }

    /**
     * 获取磁盘剩余空间
     *
     * @return 磁盘剩余空间（MB）
     */
    private static long getDiskUsedSpace() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return (statFs.getTotalBytes() - statFs.getAvailableBytes()) / (1024 * 1024);
        } else {
            return (statFs.getBlockCount() * statFs.getBlockSize() - statFs.getAvailableBlocks() * statFs.getBlockSize()) / (1024 * 1024);
        }
    }

    /**
     * 获取磁盘总空间
     *
     * @return 磁盘总空间（MB）
     */
    private static long getDiskTotalSpace() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return statFs.getTotalBytes() / (1024 * 1024);
        } else {
            return statFs.getBlockCount() * statFs.getBlockSize() / (1024 * 1024);
        }
    }

    /**
     * 获取内存信息
     *
     * @param context 上下文对象
     * @return 内存信息对象
     */
    private static ActivityManager.MemoryInfo getMemoryInfo(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo;
    }

    /**
     * 获取CPU温度
     *
     * @return CPU温度
     */
    private static float getCpuTemperature() {
        // 常见温度文件路径列表（不同设备可能不同）
        List<String> possiblePaths = new ArrayList<>();
        possiblePaths.add("/sys/class/thermal/thermal_zone0/temp");
        possiblePaths.add("/sys/class/thermal/thermal_zone1/temp");
        possiblePaths.add("/sys/devices/system/cpu/cpu0/cpufreq/cpu_temp");
        possiblePaths.add("/sys/devices/virtual/thermal/thermal_zone0/temp");

        for (String path : possiblePaths) {
            try {
                File file = new File(path);
                if (file.exists()) {
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    String line = reader.readLine();
                    reader.close();

                    if (line != null) {
                        float temp = Float.parseFloat(line.trim());
                        // 某些设备返回毫摄氏度，需要转换为摄氏度
                        return temp > 1000 ? temp / 1000 : temp;
                    }
                }
            } catch (IOException | NumberFormatException e) {
                // 忽略错误，尝试下一个路径
            }
        }
        return Float.NaN; // 未找到有效温度

    }


    /**
     * 获取CPU占用率
     *
     * @return CPU占用率
     */
    private static long getCpuUsage() {
        try {
            FileReader fr = new FileReader("/proc/stat");
            BufferedReader br = new BufferedReader(fr);
            String line = br.readLine();
            String[] toks = line.split(" ");
            long idle1 = Long.parseLong(toks[5]);
            long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                    + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

            try {
                Thread.sleep(360);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            br = new BufferedReader(new FileReader("/proc/stat"));
            line = br.readLine();
            toks = line.split(" ");
            long idle2 = Long.parseLong(toks[5]);
            long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                    + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

            return (cpu2 - cpu1) * 100 / ((cpu2 + idle2) - (cpu1 + idle1));
        } catch (IOException e) {
            Log.e(TAG, "获取CPU占用率失败: " + e.getMessage());
            return 0;
        }
    }

    /**
     * 获取WIFI状态
     *
     * @param context 上下文对象
     * @return WIFI状态字符串
     */
    @SuppressLint("WifiManagerPotentialLeak")
    private static String getWifiStatus(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled() ? "开启" : "关闭";
    }


    /**
     * 获取CPU物理核心数
     */
    public static int getPhysicalCoreCount() {
        try {
            // 尝试读取CPU核心目录
            File dir = new File("/sys/devices/system/cpu/");
            File[] files = dir.listFiles(
                    pathname -> Pattern.matches("cpu[0-9]+", pathname.getName())
            );
            return files != null ? files.length : 1;
        } catch (Exception e) {
            // 备用方案：使用Runtime类（可能包含虚拟核心）
            return Runtime.getRuntime().availableProcessors();
        }
    }

    /**
     * 获取CPU总频率（所有核心的最大频率之和，单位MHz）
     */
    public static long getTotalCpuFrequency() {
        long totalFreq = 0;
        int coreCount = getPhysicalCoreCount();

        for (int i = 0; i < coreCount; i++) {
            long freq = readCpuFreq("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq");
            totalFreq += freq;
        }

        return totalFreq / 1000; // 转换为MHz
    }

    /**
     * 从文件读取CPU频率（单位kHz）
     */
    private static long readCpuFreq(String path) {
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line = reader.readLine();
            if (line != null) {
                return Long.parseLong(line.trim());
            }
        } catch (Exception e) {
            // 忽略
        }
        return 0;
    }


    /**
     * 检查定位服务是否已启用（针对Android 4.4及以下设备）
     */
    public static boolean isLocationServiceEnabled(Context context) {
        LocationManager locationManager = (LocationManager)
                context.getSystemService(Context.LOCATION_SERVICE);

        if (locationManager == null) return false;

        // 检查GPS定位是否启用
        boolean gpsEnabled = false;
        try {
            gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception e) {
            // 忽略异常
        }

        // 检查网络定位是否启用
        boolean networkEnabled = false;
        try {
            networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception e) {
            // 忽略异常
        }

        return gpsEnabled || networkEnabled;
    }


    // 蓝牙状态常量
    public static final int BLUETOOTH_NOT_SUPPORTED = -1; // 设备不支持蓝牙
    public static final int BLUETOOTH_DISABLED = 0;      // 蓝牙已关闭
    public static final int BLUETOOTH_ENABLED = 1;       // 蓝牙已开启

    /**
     * 获取蓝牙状态（针对Android 4.4）
     */
    public static int getBluetoothStatus(Context context) {
        // 获取蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            return BLUETOOTH_NOT_SUPPORTED;
        }

        // 检查蓝牙是否已启用
        return bluetoothAdapter.isEnabled() ? BLUETOOTH_ENABLED : BLUETOOTH_DISABLED;
    }

    /**
     * 将蓝牙状态码转换为可读字符串
     */
    public static String getStatusMessage(int status) {
        switch (status) {
            case BLUETOOTH_NOT_SUPPORTED:
                return "设备不支持蓝牙";
            case BLUETOOTH_DISABLED:
                return "蓝牙已关闭";
            case BLUETOOTH_ENABLED:
                return "蓝牙已开启";
            default:
                return "获取蓝牙状态失败";
        }
    }


    // 静音状态常量
    public static final int STATUS_NORMAL = 0;      // 正常模式（有声音）
    public static final int STATUS_VIBRATE = 1;     // 振动模式
    public static final int STATUS_SILENT = 2;      // 静音 模式
    public static final int STATUS_ERROR = -1;      // 获取状态失败

    /**
     * 获取设备的声音状态
     */
    public static int getSoundStatus(Context context) {
        try {
            AudioManager audioManager = (AudioManager)
                    context.getSystemService(Context.AUDIO_SERVICE);

            if (audioManager == null) {
                return STATUS_ERROR;
            }

            // 不同版本的API处理
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Android 6.0及以上使用ringerMode
                int ringerMode = audioManager.getRingerMode();
                switch (ringerMode) {
                    case AudioManager.RINGER_MODE_NORMAL:
                        return STATUS_NORMAL;
                    case AudioManager.RINGER_MODE_VIBRATE:
                        return STATUS_VIBRATE;
                    case AudioManager.RINGER_MODE_SILENT:
                        return STATUS_SILENT;
                    default:
                        return STATUS_ERROR;
                }
            } else {
                // Android 6.0以下使用getVibrateSetting和getRingerMode
                int ringerMode = audioManager.getRingerMode();
                if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
                    return STATUS_SILENT;
                } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
                    return STATUS_VIBRATE;
                } else {
                    // 检查是否处于振动状态（即使铃声模式为NORMAL）
                    int vibrateSetting = audioManager.getVibrateSetting(
                            AudioManager.VIBRATE_TYPE_RINGER);

                    if (vibrateSetting == AudioManager.VIBRATE_SETTING_ON ||
                            vibrateSetting == AudioManager.VIBRATE_SETTING_ONLY_SILENT) {
                        return STATUS_VIBRATE;
                    } else {
                        return STATUS_NORMAL;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return STATUS_ERROR;
        }
    }

    /**
     * 将状态码转换为可读字符串
     */
    public static String getMuteStatusMessage(int status) {
        switch (status) {
            case STATUS_NORMAL:
                return "正常模式";
            case STATUS_VIBRATE:
                return "振动模式";
            case STATUS_SILENT:
                return "静音模式";
            case STATUS_ERROR:
            default:
                return "获取状态失败";
        }
    }


    /**
     * 获取设备自开机以来的上行总流量（字节）
     */
    public static long getTotalTxBytes() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android 6.0及以上：获取所有网络接口的总上行流量
            return TrafficStats.getTotalTxBytes();
        } else {
            // Android 6.0以下：分别获取移动网络和WiFi的上行流量
            long mobileTxBytes = TrafficStats.getMobileTxBytes();
            long totalTxBytes = TrafficStats.getTotalTxBytes();

            // 计算非移动网络的上行流量（主要是WiFi）
            long nonMobileTxBytes = totalTxBytes - mobileTxBytes;

            // 返回总上行流量
            return totalTxBytes;
        }
    }

    /**
     * 获取设备自开机以来的移动网络上行流量（字节）
     */
    public static long getMobileTxBytes() {
        return TrafficStats.getMobileTxBytes();
    }


    /**
     * 获取设备自开机以来的下行总流量（字节）
     */
    public static long getTotalRxBytes() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android 6.0及以上：获取所有网络接口的总下行流量
            return TrafficStats.getTotalRxBytes();
        } else {
            // Android 6.0以下：分别获取移动网络和WiFi的下行流量
            long mobileRxBytes = TrafficStats.getMobileRxBytes();
            long totalRxBytes = TrafficStats.getTotalRxBytes();

            // 计算非移动网络的下行流量（主要是WiFi）
            long nonMobileRxBytes = totalRxBytes - mobileRxBytes;

            // 返回总下行流量
            return totalRxBytes;
        }
    }

    /**
     * 获取设备自开机以来的移动网络下行流量（字节）
     */
    public static long getMobileRxBytes() {
        return TrafficStats.getMobileRxBytes();
    }

    /**
     * 将字节转换为可读的流量单位
     */
    public static String formatBytes(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.2f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.2f MB", bytes / (1024.0 * 1024.0));
        } else {
            return String.format("%.2f GB", bytes / (1024.0 * 1024.0 * 1024.0));
        }
    }


    private static long lastTxBytes = TrafficStats.UNSUPPORTED;
    private static long lastSampleTime = 0;

    /**
     * 获取当前上行带宽（KB/S）
     * 需每10秒调用一次以获取准确数据
     */
    public static float getCurrentUploadBandwidth() {
        long currentTxBytes = TrafficStats.getTotalTxBytes();
        long currentTime = System.currentTimeMillis();

        // 首次调用，初始化基准值
        if (lastTxBytes == TrafficStats.UNSUPPORTED) {
            lastTxBytes = currentTxBytes;
            lastSampleTime = currentTime;
            return 0; // 首次调用无法计算，返回0
        }

        // 计算时间间隔（秒）
        float intervalSec = (currentTime - lastSampleTime) / 1000.0f;

        // 计算上行流量（KB）
        float txBytes = (currentTxBytes - lastTxBytes) / 1024.0f;

        // 计算上行带宽（KB/S）
        float uploadBandwidth = intervalSec > 0 ? txBytes / intervalSec : 0;

        // 更新最后采样数据
        lastTxBytes = currentTxBytes;
        lastSampleTime = currentTime;

        return uploadBandwidth;
    }

    private static long lastRxBytes = TrafficStats.UNSUPPORTED;
    private static long lastRxSampleTime = 0;

    /**
     * 获取当前下行带宽（KB/S）
     * 需每10秒调用一次以获取准确数据
     */
    public static float getCurrentDownloadBandwidth() {
        long currentRxBytes = TrafficStats.getTotalRxBytes();
        long currentTime = System.currentTimeMillis();

        // 首次调用，初始化基准值
        if (lastRxBytes == TrafficStats.UNSUPPORTED) {
            lastRxBytes = currentRxBytes;
            lastRxSampleTime = currentTime;
            return 0; // 首次调用无法计算，返回0
        }

        // 计算时间间隔（秒）
        float intervalSec = (currentTime - lastRxSampleTime) / 1000.0f;

        // 计算下行流量（KB）
        float rxBytes = (currentRxBytes - lastRxBytes) / 1024.0f;

        // 计算下行带宽（KB/S）
        float downloadBandwidth = intervalSec > 0 ? rxBytes / intervalSec : 0;

        // 更新最后采样数据
        lastRxBytes = currentRxBytes;
        lastRxSampleTime = currentTime;

        return downloadBandwidth;
    }


}